<template>
  <!--  回收客户组件 -->
  <div>
    <el-button type="primary" size="mini" @click.stop="clickRecoveryBtn"
      >回收</el-button
    >
    <!-- 批量回收模态框 -->
    <el-dialog
      :close-on-click-modal="false"
      :show-close="true"
      :append-to-body="true"
      width="46%"
      :visible.sync="dialogFormVisible2"
      @closed="
        numForm.num = '';
        roamRemarks = null;
      "
      @open="
        $store.commit('CHANGEBTNSTATUS', false);
        receiveId = [];
      "
    >
      <el-form label-width="130px" :rules="rules" :model="numForm" ref="form">
        <el-form-item label="是否保留客户计划">
          <el-select size="mini" v-model="isPlan" placeholder="">
            <el-option label="保留" value="1"></el-option>
            <el-option label="不保留" value="0"></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="请选择被分配人" :label-width="formLabelWidth">
          <el-cascader
            size="mini"
            ref="person"
            v-model="receiveId"
            :options="options"
            :props="props"
            clearable
            :show-all-levels="false"
            collapse-tags
          ></el-cascader>
        </el-form-item>
        <el-form-item label="回收条数" prop="num">
          <el-input v-model="numForm.num" size="mini"></el-input>
        </el-form-item>
        <el-row>
          <el-col>
            <el-form-item label="回收备注">
              <el-input
                type="textarea"
                v-model="roamRemarks"
                size="mini"
              ></el-input>
            </el-form-item>
          </el-col>
        </el-row>
        <el-form-item>
          <el-button
            size="mini"
            type="primary"
            @click="More"
            :disabled="$store.state.btnDisabled"
            >确认</el-button
          >
          <el-button
            size="mini"
            type="primary"
            :disabled="$store.state.btnDisabled"
            @click="dialogFormVisible2 = false"
            >取消</el-button
          >
        </el-form-item>
      </el-form>
    </el-dialog>
    <!-- 单个 -->
    <el-dialog
      @closed="roamRemarks = null"
      :append-to-body="true"
      width="46%"
      :visible.sync="dialogFormVisible"
      @open="
        $store.commit('CHANGEBTNSTATUS', false);
        selectPer.ownerid=null;
        selectPer.ownerName = null;
      "
      label-width="130px"
      :close-on-click-modal="false"
      :show-close="true"
    >
      <el-form>
        <el-form-item label="是否保留客户计划">
          <el-select size="mini" v-model="isPlan" placeholder="">
            <el-option label="保留" value="1"></el-option>
            <el-option label="不保留" value="0"></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="请选择被分配人" :label-width="formLabelWidth">
          <el-cascader
            clearable
            size="mini"
            ref="person"
            v-model="selectPer.ownerid"
            :options="options2"
            :props="props2"
            @change="showPerson"
            :show-all-levels="false"
          ></el-cascader>
        </el-form-item>
        <el-row>
          <el-col>
            <el-form-item label="回收备注">
              <el-input
                type="textarea"
                v-model="roamRemarks"
                size="mini"
              ></el-input>
            </el-form-item>
          </el-col>
        </el-row>
        <el-form-item>
          <el-button
            size="mini"
            type="primary"
            @click="sel"
            :disabled="$store.state.btnDisabled"
            >确认</el-button
          >
          <el-button
            size="mini"
            type="primary"
            :disabled="$store.state.btnDisabled"
            @click="dialogFormVisible = false"
            >取消</el-button
          >
        </el-form-item>
      </el-form>
    </el-dialog>
    <!-- 继续分配模态框 -->
    <el-dialog
    :close-on-click-modal="false"
      :append-to-body="true"
      width="30%"
      @close="
        nameArr = [];
        disArr_sure = [];
        updateList();
      "
      title="该客户是从该人员处回收，是否将其继续分配？"
      :visible.sync="dialogFormVisible3"
      @open="$store.commit('CHANGEBTNSTATUS', false)"
    >
      <div slot="footer" class="dialog-footer">
        <el-button size="mini" :disabled="$store.state.btnDisabled" @click="dialogFormVisible3 = false"
          >否</el-button
        >
        <el-button
          size="mini"
          type="primary"
          :disabled="$store.state.btnDisabled"
          @click="sure_two()"
          >是</el-button
        >
      </div>
    </el-dialog>
    <!-- 批量继续分配模态框 -->
    <el-dialog
    :close-on-click-modal="false"
      :append-to-body="true"
      width="30%"
      @close="
        nameArr = [];
        disArr_sure = [];
        updateList();
      "
      title="以下金融顾问有客户被重复分配，是否将其加入分配数据进行继续？"
      :visible.sync="dialogFormVisible4"
      @open="$store.commit('CHANGEBTNSTATUS', false)"
    >
      <div>
        <div class="divBox" v-for="(value, key) in repeatMap" :key="key">
          {{ key }}:<span>{{ value }}</span>条
        </div>
      </div>
      <div slot="footer" class="dialog-footer">
        <el-button size="mini" :disabled="$store.state.btnDisabled" @click="randomAllocation2()">分配剩余数据</el-button>
        <el-button
          size="mini"
          type="primary"
          :disabled="$store.state.btnDisabled"
          @click="randomAllocation1()"
          >是</el-button
        >
      </div>
    </el-dialog>
  </div>
</template>

<script>
import local from "@/utils/local.js";
import { Message } from "element-ui";
import Api from "@/http/apis/modules/custManagement.js";
export default {
  props: {
    recoveryArr: {
      type: Array,
      default: [],
    },
    searchForm: {
      type: String,
      default: "",
    },
  },
  data() {
    return {
      // 回收数据
      userInfo: this.$store.state.user,
      isPlan: "1", //是否保留
      numForm: {
        num: "",
      }, //回收条数
      roamRemarks: null, //回收备注
      // 回收模态框
      dialogFormVisible: false,
      dialogFormVisible2: false,
      formLabelWidth: "120px",
      disArr: [], //分配数据
      dialogDistribution: false, // 分配模态框
      dialogFormVisible3: false, // 继续分配模态框
      props: {
        value: "id",
        label: "name",
        children: "child",
        multiple: true,
        emitPath:false
      },
      options: [],
      props2: {
        value: "id",
        label: "name",
        children: "child",
        emitPath: false,
      },
      options2: [],
      // 联动 //选中人员
      selectPer: {
        ownerName: "",
        ownerid: "",
      },
      nameArr: [],
      disArr_sure: [],
      customerMangers: [], //被分配人多选
      receiveId: [],
      dialogFormVisible4: false,
      nameArr2: [],
      collect: [], //正常据
      repeat: [], //重复数据
      repeatMap: {}, // 重复人员个数以及金融顾问
      rules: {
        num: [{ required: true, message: "不能为空", trigger: "blur" }],
      },
    };
  },
  methods: {
    updateList() {
      this.$emit("getUpdateList");
    },
    //点击回收按钮
    clickRecoveryBtn() {
      if (this.recoveryArr.length == 0) {
        this.text();
        this.dialogFormVisible2 = true;
      } else {
        this.text();
        this.dialogFormVisible = true;
      }
    },
    // 单个操作
    sel() {
      // 没选取分配人，回收
      if (this.selectPer.ownerName == "" || this.selectPer.ownerName == null) {
        this.back_sure(1);
      } else {
        // 选取了分配人，回收并分配
        this.back_sure(2);
      }
    },
    // 确认回收/单个
    async back_sure(type) {
       this.$store.commit("CHANGEBTNSTATUS", true);
      // 处理回收数据
      let nameArr = ["customerId", "oldOwnerId"];
      let selObj = {};
      let recoveryArr = [];
      this.recoveryArr.map((item) => {
        for (let key in item) {
          if (nameArr.includes(key)) {
            selObj[key] = item[key];
          }
          selObj["focusOn"] =
            item["focusOn"] == null || item["focusOn"] == 0 ? 0 : 1;
        }
        // 公共信息
        selObj.recycledId = item.ownerId;
        selObj.isPlan = this.isPlan;
        selObj.ownerId = this.$store.state.user.userId;
        selObj.leftTime = item.leftTime;
        selObj.roamRemarks = this.roamRemarks;
        recoveryArr.push(selObj);
        selObj = {};
      });
      let re = await Api.toAllocatedApi(recoveryArr);
      let { code, msg } = re.data;
      if (code === "SUCCESS") {
        Message({
          type: "success",
          message: "回收成功",
        });
        this.disArr = this.recoveryArr;
        if (type == 1) {
          this.$emit("getUpdateList");
        } else if (type == 2) {
          this.clickDistributionBtn();
        }
        this.$store.commit("CHANGEBTNSTATUS", false);
      } else {
        Message.error("回收失败");
        this.$store.commit("CHANGEBTNSTATUS", false);
      }
      recoveryArr = [];
      this.dialogFormVisible = false;
    },
    // 获取人员信息
    async text() {
      let re = await Api.chooseMangerApi({
        userId: this.$store.state.user.userId,
      });
      this.options = re.data.result;
      this.options2 = re.data.result;
    },
    // 选取分配人员，单个分配
    showPerson() {
      let personData = this.$refs.person.getCheckedNodes(true);
      if (personData.length > 0) {
        this.selectPer.ownerName = personData[0].label;
        this.selectPer.ownerid = personData[0].value;
      } else {
        this.selectPer.ownerName = null;
        this.selectPer.ownerid = null;
      }
    },
    // 立即分配
    async clickDistributionBtn() {
      if (this.selectPer.ownerName == "") {
        Message.error("请选择分配人员！");
      } else {
        this.$store.commit("CHANGEBTNSTATUS", true);
        this.disArr.forEach((item) => {
          for (let key in item) {
            item.assignOwnerId = this.selectPer.ownerid;
            item.roamRemarks = this.roamRemarks;
            item.isContinue = null;
            item.createbyid = this.$store.state.user.userId;
          }
        });
        let re = await Api.bachDistributionApi(this.disArr);
        let { code, msg } = re.data;
        if (re.data.result.result.length == 0) {
          Message({
            type: "success",
            message: msg,
          });
          this.$emit("getUpdateList");
          this.$store.commit("CHANGEBTNSTATUS", false);
          this.selectPer = {};
          this.dialogDistribution = false;
        } else {
          this.$store.commit("CHANGEBTNSTATUS", false);
          this.dialogDistribution = false;
          let nameArr = [];
          re.data.result.result.forEach((item) => {
            nameArr.push(item.customerName);
          });
          this.nameArr = nameArr;
          nameArr = [];
          this.dialogFormVisible3 = true;
          //接收未分配成功人员数据
          this.disArr_sure = re.data.result.result;
        }
      }
    },
    // 再次确认分配
    async sure_two() {
       this.$store.commit("CHANGEBTNSTATUS", true);
      this.disArr_sure.forEach((item) => {
        for (let key in item) {
          item.receiveId = this.receiveId.length>0?this.receiveId:null;
          item.roamRemarks = this.roamRemarks;
          item.isContinue = "1";
          item.createbyid = this.$store.state.user.userId;
        }
      });
      let re = await Api.bachDistributionApi(this.disArr_sure);
      let { code, msg } = re.data;
      if (code === "SUCCESS") {
        Message({
          type: "success",
          message: msg,
        });
        this.selectPer = {};
        this.$emit("getUpdateList");
        this.dialogFormVisible3 = false;
        this.$store.commit("CHANGEBTNSTATUS", false);
      } else {
        this.$store.commit("CHANGEBTNSTATUS", false);
        Message.error(msg);
      }
    },
    // 批量操作
    More() {
      this.$refs.form.validate(async (valid) => {
        if (valid) {
          //未选取被分配人，直接回收
          if (
            this.receiveId.length == 0 
          ) {
            this.back_sure3();
          } else {
            this.back_sure2();
          }
        } else {
          return;
        }
      });
    },
    // 批量回收
    async back_sure3() {
      this.$store.commit("CHANGEBTNSTATUS", true);
      let data = {
        ownerId: this.$store.state.user.userId,
        recoveryNumber: this.numForm.num,
        isPlan: this.isPlan,
        roamRemarks: this.roamRemarks,
        ...JSON.parse(this.searchForm),
      };
      let re = await Api.toAllocatedMoreApi2(data);
      let { code, msg } = re.data;
      if (code === "SUCCESS") {
        Message({
          type: "success",
          message: "回收成功",
        });
        this.$emit("getUpdateList");
        this.$store.commit("CHANGEBTNSTATUS", false);
      } else {
        Message.error("回收失败");
        this.$store.commit("CHANGEBTNSTATUS", false);
      }
      this.dialogFormVisible2 = false;
    },
    // 批量回收并分配
    async back_sure2() {
      this.$store.commit("CHANGEBTNSTATUS", true);
      let data = {
        ownerId: this.$store.state.user.userId,
        recoveryNumber: this.numForm.num,
        isPlan: this.isPlan,
        roamRemarks: this.roamRemarks,
        ...JSON.parse(this.searchForm),
      };
      let re = await Api.toAllocatedMoreApi(data);
      let { code, msg } = re.data;
      if (code === "SUCCESS") {
        Message({
          type: "success",
          message: "回收成功",
        });
        this.disArr = re.data.result;
        this.randomAllocation();
        this.$store.commit("CHANGEBTNSTATUS", false);
      } else {
        Message.error("回收失败");
        this.$store.commit("CHANGEBTNSTATUS", false);
      }
      this.dialogFormVisible2 = false;
     
    },
    // 随机分配
    async randomAllocation() {
      this.$store.commit("CHANGEBTNSTATUS", true);
      let Arr = [];
      this.disArr.forEach((item) => {
        let sel = {};
        sel.customerId = item.customerId;
        sel.customerName = item.customerName;
        sel.ownerName = item.ownerName;
        sel.oldOwnerId = item.oldOwnerId;
        sel.ownerId = item.ownerId;
        sel.receiveId = this.receiveId.length>0?this.receiveId:null;
        sel.roamRemarks = this.roamRemarks;
        sel.isContinue = null;
        Arr.push(sel);
      });
      let re = await Api.randomAllocationApi(Arr);
      let { code, msg } = re.data;
      if (code == "SUCCESS") {
        this.collect = re.data.result.result.collect;
        this.repeat = re.data.result.result.repeat;
        this.repeatMap = re.data.result.result.repeatMap;
        if (re.data.result.result.repeat.length != 0) {
          this.dialogFormVisible4 = true;
        } else {
          this.randomAllocation2();
        }
        this.$store.commit("CHANGEBTNSTATUS", false);
      } else {
        Message.error(msg);
        this.$store.commit("CHANGEBTNSTATUS", false);
      }
    },
    // 随机分配是
    async randomAllocation1() {
      this.$store.commit("CHANGEBTNSTATUS", true);
      let Arr = [];
      let concatArr = this.collect.concat(this.repeat);
      concatArr.forEach((item) => {
        let sel = {};
        sel.customerId = item.customerId;
        sel.oldOwnerId = item.oldOwnerId;
        sel.ownerId = item.ownerId;
        sel.receiveId = this.receiveId.length>0?this.receiveId:null;
        sel.roamRemarks = this.roamRemarks;
        sel.isContinue = "1";
        Arr.push(sel);
      });
      let re = await Api.randomAllocationApi(Arr);
      let { code, msg } = re.data;
      if (code == "SUCCESS") {
        Message({
          type: "success",
          message: msg,
        });
        this.$store.commit("CHANGEBTNSTATUS", false);
      } else {
        Message.error(msg);
        this.$store.commit("CHANGEBTNSTATUS", false);
      }
      this.$emit("getUpdateList");
      this.dialogFormVisible4 = false;
    },
    //随机分配否
    async randomAllocation2() {
      this.$store.commit("CHANGEBTNSTATUS", true);
      let Arr = [];
      this.collect.forEach((item) => {
        let sel = {};
        sel.customerId = item.customerId;
        sel.oldOwnerId = item.oldOwnerId;
        sel.ownerId = item.ownerId;
        sel.receiveId = this.receiveId.length>0?this.receiveId:null;
        sel.roamRemarks = this.roamRemarks;
        sel.isContinue = "1";
        Arr.push(sel);
      });
      let re = await Api.randomAllocationApi(Arr);
      let { code, msg } = re.data;
      if (code == "SUCCESS") {
        Message({
          type: "success",
          message: msg,
        });
        this.$store.commit("CHANGEBTNSTATUS", false);
      } else {
        Message.error(msg);
        this.$store.commit("CHANGEBTNSTATUS", false);
      }
      this.$emit("getUpdateList");
      this.dialogFormVisible4 = false;
    },
  },
};
</script>

<style lang="less" scoped>
/* 遮罩 */
#mask {
  width: 100%;
  height: 100%;
  position: fixed;
  top: 0;
  left: 0;
  z-index: 10000;
}
.el-dialog__body {
  position: relative;
}
.divBox {
  line-height: 30px;
  font-size: 18px;
  span{
    color:#f00;
    margin:0 3px;
  }
}
</style>
